﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.BasicData.Application
{
    public class SupplierServices : ISupplierServices
    {
        private readonly IBaseRepository<SupplierModel> supplier;
        private readonly IMapper mapper;

        public SupplierServices(IBaseRepository<SupplierModel> supplier, IMapper mapper)
        {
            this.supplier = supplier;
            this.mapper = mapper;
        }
        public ApiResult<int> AddSupplier(SupplierModel model)
        {
            //根据id判断是添加还是修改有id就是修改没有就是添加
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                int rows = 0;
                if (model.Id > 0)
                {
                    //修改
                    // 获取原始数据
                    var existingModel = supplier.GetValue(x => x.Id == model.Id && !x.IsDeleted);
                    if (existingModel == null)
                    {
                        result.Code = ApiEnums.Fail;
                        result.Message = "供应商不存在";
                        result.Data = 0;
                        return result;
                    }
                    
                    // 手动更新属性
                    existingModel.Suppliercode = model.Suppliercode;
                    existingModel.Suppliername = model.Suppliername;
                    existingModel.Supplierabbreviation = model.Supplierabbreviation;
                    existingModel.Suppliercontactinformation = model.Suppliercontactinformation;
                    existingModel.Supplieraddress = model.Supplieraddress;
                    existingModel.Suppliercreditcode = model.Suppliercreditcode;
                    existingModel.Supplierremarks = model.Supplierremarks;
                    existingModel.UpdatedTime = DateTime.Now;
                    existingModel.UpdatedBy = "张三";
                   

                    
                    rows = supplier.Update(existingModel);
                }
                else
                {
                    //添加
                    // 使用AutoMapper创建新对象
                    var newModel = mapper.Map<SupplierModel>(model);
                    newModel.CreatedTime = DateTime.Now;
                    newModel.Id = YitIdHelper.NextId();
                    newModel.UpdatedTime = DateTime.Now;
                    newModel.IsDeleted = false;
                    
                    rows = supplier.Add(newModel);
                }

                if (rows > 0)
                {
                    result.Code = ApiEnums.Success;
                    result.Message = "操作成功";
                    result.Data = rows;
                }
                else
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "操作失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = 0;
            }
            return result;
        }

        public ApiResult<int> DeleteSupplier(long id)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var model = supplier.GetValue(x => x.Id == id && !x.IsDeleted);
                if (model == null)
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "供应商不存在";
                    result.Data = 0;
                    return result;
                }

                // 逻辑删除
                model.IsDeleted = true;
                model.UpdatedTime = DateTime.Now;
                int rows = supplier.Update(model);

                if (rows > 0)
                {
                    result.Code = ApiEnums.Success;
                    result.Message = "删除成功";
                    result.Data = rows;
                }
                else
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "删除失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = 0;
            }
            return result;
        }

        public ApiResult<List<SupplierModel>> GetAllSupplier()
        {
            ApiResult<List<SupplierModel>> result = new ApiResult<List<SupplierModel>>();
            try
            {
                var list = supplier.GetAll().Where(x => !x.IsDeleted).ToList();
                
                result.Code = ApiEnums.Success;
                result.Message = "获取成功";
                result.Data = list;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = new List<SupplierModel>();
            }
            return result;
        }

        public ApiPaging<SupplierModel> GetSupplier(string? Suppliercode, string? Suppliername, int pageindex, int pagesize)
        {
            ApiPaging<SupplierModel> result = new ApiPaging<SupplierModel>();
            try
            {
                // 构建查询条件
                var query = supplier.GetAll().Where(x => !x.IsDeleted);
                
                // 根据供应商编码筛选
                if (!string.IsNullOrEmpty(Suppliercode))
                {
                    query = query.Where(x => x.Suppliercode.Contains(Suppliercode));
                }
                
                // 根据供应商名称筛选
                if (!string.IsNullOrEmpty(Suppliername))
                {
                    query = query.Where(x => x.Suppliername.Contains(Suppliername));
                }

                // 计算总记录数
                int totalCount = query.Count();
                
                // 分页查询
                var list = query.Skip((pageindex - 1) * pagesize)
                               .Take(pagesize)
                               .ToList();

                result.Code = ApiEnums.Success;
                result.Message = "获取成功";
                result.Data = null; // ApiResult<SupplierModel>的Data属性不适用于列表
                result.TotalCount = totalCount;
                result.PageNum = pageindex;
                result.PageSize = pagesize;
                result.PageData = list; // 正确赋值，PageData是List<SupplierModel>
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = null;
                result.PageData = new List<SupplierModel>(); // 确保PageData不为null
                result.TotalCount = 0;
            }
            return result;
        }

        public ApiResult<SupplierModel> GetSupplierById(long id)
        {
            ApiResult<SupplierModel> result = new ApiResult<SupplierModel>();
            try
            {
                var model = supplier.GetValue(x => x.Id == id && !x.IsDeleted);
                if (model != null)
                {
                    result.Code = ApiEnums.Success;
                    result.Message = "获取成功";
                    result.Data = model;
                }
                else
                {
                    result.Code = ApiEnums.Fail;
                    result.Message = "供应商不存在";
                    result.Data = null;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnums.Error;
                result.Message = $"系统异常：{ex.Message}";
                result.Data = null;
            }
            return result;
        }
    }
}
